package com.midele.goodstuff.data.repository.net_util

import com.midele.goodstuff.MainApplication
import com.midele.goodstuff.util.DataStoreUtils
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object NetworkConfig {

    // 基础URL
    //private const val BASE_URL = "http://192.168.1.53:16061/app-api/"
    //private const val BASE_URL = "http://zhuapp.mideyouapp.top:7009/app-api/"
    private const val BASE_URL = "https://app.chtvnetwork.com/app-api/"

    // 超时时间
    private const val TIMEOUT = 15 * 1000L

    private val okHttpClient by lazy {
        OkHttpClient.Builder()
            .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
            .readTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
            .writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
            .cookieJar(SimpleCookieJar())
            .addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            })

            .addInterceptor { chain ->
                val original = chain.request()
                val shareLinkId = DataStoreUtils.readDataBlocking(
                    MainApplication.instance,
                    DataStoreUtils.PrefKeys.SHARE_LINK_ID,
                    ""
                )
                val request = original.newBuilder()
                    .header("Content-Type", "application/json")
                    .header("Accept", "application/json")
                    .header("X-DistributorLink-Id", shareLinkId)
                    //.header("token", token)
                    // 可以在这里添加token等通用header
                    // .header("Authorization", "Bearer ${getToken()}")
                    .method(original.method, original.body)
                    .build()

                //LogUtils.d("NetworkConfig","header ${request.headers.toString()}")

                chain.proceed(request)

            }.build()
    }

    private val retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }


    fun <T> createService(service: Class<T>?): T {
        if (service == null) {
            throw RuntimeException("Api service is null!")
        }
        return retrofit.create(service)
    }
}